package com.showworkflow.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class JsonUtils {
    // 移除所有高版本方法，确保兼容旧版Jackson
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public static Map<String, Object> parseJson(String utf8Json) {
        try {
            // 清理可能的Markdown代码块标记
            String cleanedJson = utf8Json.trim();
            if (cleanedJson.startsWith("```json")) {
                cleanedJson = cleanedJson.substring(7);
            }
            if (cleanedJson.startsWith("```")) {
                cleanedJson = cleanedJson.substring(3);
            }
            if (cleanedJson.endsWith("```")) {
                cleanedJson = cleanedJson.substring(0, cleanedJson.length() - 3);
            }
            cleanedJson = cleanedJson.trim();

            // 双重UTF-8转换，确保中文不丢失（兼容所有版本）
            String normalizedJson = new String(cleanedJson.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
            return OBJECT_MAPPER.readValue(normalizedJson, new TypeReference<Map<String, Object>>() {});
        } catch (Exception e) {
            throw new RuntimeException("JSON解析失败（兼容模式）", e);
        }
    }

    public static String toJson(Object obj) {
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException("对象转JSON失败", e);
        }
    }
}
    